package com.hyjr.RxTask.netty.server;

import java.net.InetSocketAddress;

import com.hyjr.RxTask.netty.handler.ReceiveTaskServerHandler;
import com.hyjr.common.utils.LogUtils;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class ReceiveTaskServer {
	
	public void start(Integer port) throws Exception {
		NioEventLoopGroup group = new NioEventLoopGroup();
		
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							LogUtils.debug("检测端，服务端ReceiveTaskServer：有客户端连接上来:" + ch.localAddress().toString());
							ch.pipeline().addLast(new ObjectEncoder());
							ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE,
									ClassResolvers.weakCachingConcurrentResolver(null))); // 最大长度
							ch.pipeline().addLast(new ReceiveTaskServerHandler());
						}
					});
			ChannelFuture f = b.bind().sync();
			LogUtils.debug("检测端，服务端ReceiveTaskServer：started and listen on " + f.channel().localAddress());
			f.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();
		}
	}
}
